/**
 * WebRTC语音聊天管理器
 * 支持开发测试模式和生产环境
 */

class WebRTCManager {
  constructor(store) {
    this.store = store;
    this.peerConnections = new Map(); // playerId -> RTCPeerConnection
    this.localStream = null;
    this.remoteStreams = new Map(); // playerId -> MediaStream
    this.isTestMode = process.env.NODE_ENV === 'development';
    
    // WebRTC配置
    this.rtcConfiguration = {
      iceServers: [
        // Google 免费 STUN 服务器
        { urls: 'stun:stun.l.google.com:19302' },
        { urls: 'stun:stun1.l.google.com:19302' },
        { urls: 'stun:stun2.l.google.com:19302' },
        
        // Mozilla 免费 STUN 服务器
        { urls: 'stun:stun.services.mozilla.com' },
        
        // 备用免费STUN服务器
        { urls: 'stun:stun.stunprotocol.org:3478' }
      ]
    };

    // 测试模式配置
    this.testConfig = {
      simulateLatency: 100, // 模拟延迟(ms)
      simulatePacketLoss: 0.02, // 模拟丢包率(2%)
      simulateJitter: 20, // 模拟抖动(ms)
    };

    console.log(`🎙️ WebRTC Manager initialized (${this.isTestMode ? 'TEST' : 'PRODUCTION'} mode)`);
  }

  /**
   * 初始化本地音频流
   */
  async initializeLocalStream() {
    try {
      if (this.isTestMode) {
        // 开发模式：创建模拟音频流
        this.localStream = await this.createMockAudioStream();
        console.log('🧪 Mock audio stream created for testing');
      } else {
        // 生产模式：获取真实麦克风
        this.localStream = await navigator.mediaDevices.getUserMedia({
          audio: {
            echoCancellation: true,
            noiseSuppression: true,
            autoGainControl: true,
            sampleRate: 16000, // 节省带宽
            channelCount: 1, // 单声道
          }
        });
        console.log('🎤 Real microphone access granted');
      }

      // 更新store状态
      this.store.commit('voiceChat/setLocalStream', this.localStream);
      
      return true;
    } catch (error) {
      console.error('❌ Failed to initialize audio stream:', error);
      return false;
    }
  }

  /**
   * 创建模拟音频流（开发测试用）
   */
  async createMockAudioStream() {
    const audioContext = new AudioContext();
    
    // 创建静音轨道
    const oscillator = audioContext.createOscillator();
    const gainNode = audioContext.createGain();
    const destination = audioContext.createMediaStreamDestination();
    
    // 设置为静音（开发时不产生噪音）
    gainNode.gain.value = 0;
    oscillator.frequency.value = 440; // A4音符
    
    oscillator.connect(gainNode);
    gainNode.connect(destination);
    
    oscillator.start();
    
    // 添加测试用的语音活动检测
    this.simulateVoiceActivity(destination.stream);
    
    return destination.stream;
  }

  /**
   * 模拟语音活动检测（测试用）
   */
  simulateVoiceActivity(stream) {
    if (!this.isTestMode) return;

    // 模拟周期性的语音活动
    setInterval(() => {
      if (Math.random() > 0.8) { // 20%的概率模拟说话
        console.log('🗣️ Simulating voice activity');
        
        // 触发语音活动事件
        const event = new CustomEvent('voiceActivity', {
          detail: { 
            active: true, 
            volume: Math.random() * 100,
            timestamp: Date.now()
          }
        });
        window.dispatchEvent(event);
        
        // 3秒后停止
        setTimeout(() => {
          const stopEvent = new CustomEvent('voiceActivity', {
            detail: { 
              active: false, 
              volume: 0,
              timestamp: Date.now()
            }
          });
          window.dispatchEvent(stopEvent);
        }, 3000);
      }
    }, 5000);
  }

  /**
   * 与指定玩家建立P2P连接
   */
  async connectToPlayer(playerId, isInitiator = false) {
    if (this.peerConnections.has(playerId)) {
      console.log(`🔗 Connection to ${playerId} already exists`);
      return this.peerConnections.get(playerId);
    }

    try {
      const peerConnection = new RTCPeerConnection(this.rtcConfiguration);
      
      // 添加本地音频流
      if (this.localStream) {
        this.localStream.getTracks().forEach(track => {
          peerConnection.addTrack(track, this.localStream);
        });
      }

      // 处理接收到的远程音频
      peerConnection.ontrack = (event) => {
        console.log(`📥 Received remote stream from ${playerId}`);
        const remoteStream = event.streams[0];
        this.remoteStreams.set(playerId, remoteStream);
        this.store.commit('voiceChat/addRemoteStream', { playerId, stream: remoteStream });
        
        // 播放远程音频
        this.playRemoteAudio(playerId, remoteStream);
      };

      // ICE候选处理
      peerConnection.onicecandidate = (event) => {
        if (event.candidate) {
          this.sendSignalingMessage(playerId, {
            type: 'ice-candidate',
            candidate: event.candidate
          });
        }
      };

      // 连接状态监控
      peerConnection.onconnectionstatechange = () => {
        const state = peerConnection.connectionState;
        console.log(`🔗 Connection to ${playerId} state: ${state}`);
        
        this.updateConnectionState(playerId, state);
        
        if (state === 'failed' || state === 'disconnected') {
          this.handleConnectionFailure(playerId);
        }
      };

      this.peerConnections.set(playerId, peerConnection);

      // 如果是发起方，创建offer
      if (isInitiator) {
        await this.createOffer(playerId);
      }

      return peerConnection;
    } catch (error) {
      console.error(`❌ Failed to connect to ${playerId}:`, error);
      throw error;
    }
  }

  /**
   * 创建WebRTC Offer
   */
  async createOffer(playerId) {
    const peerConnection = this.peerConnections.get(playerId);
    if (!peerConnection) return;

    try {
      const offer = await peerConnection.createOffer({
        offerToReceiveAudio: true,
        offerToReceiveVideo: false
      });
      
      await peerConnection.setLocalDescription(offer);
      
      this.sendSignalingMessage(playerId, {
        type: 'offer',
        offer: offer
      });
      
      console.log(`📤 Offer sent to ${playerId}`);
    } catch (error) {
      console.error(`❌ Failed to create offer for ${playerId}:`, error);
    }
  }

  /**
   * 处理WebRTC Offer
   */
  async handleOffer(fromPlayerId, offer) {
    try {
      // 如果连接不存在，创建新连接
      if (!this.peerConnections.has(fromPlayerId)) {
        await this.connectToPlayer(fromPlayerId, false);
      }

      const peerConnection = this.peerConnections.get(fromPlayerId);
      await peerConnection.setRemoteDescription(offer);
      
      const answer = await peerConnection.createAnswer();
      await peerConnection.setLocalDescription(answer);
      
      this.sendSignalingMessage(fromPlayerId, {
        type: 'answer',
        answer: answer
      });
      
      console.log(`📤 Answer sent to ${fromPlayerId}`);
    } catch (error) {
      console.error(`❌ Failed to handle offer from ${fromPlayerId}:`, error);
    }
  }

  /**
   * 处理WebRTC Answer
   */
  async handleAnswer(fromPlayerId, answer) {
    try {
      const peerConnection = this.peerConnections.get(fromPlayerId);
      if (peerConnection) {
        await peerConnection.setRemoteDescription(answer);
        console.log(`📥 Answer received from ${fromPlayerId}`);
      }
    } catch (error) {
      console.error(`❌ Failed to handle answer from ${fromPlayerId}:`, error);
    }
  }

  /**
   * 处理ICE候选
   */
  async handleIceCandidate(fromPlayerId, candidate) {
    try {
      const peerConnection = this.peerConnections.get(fromPlayerId);
      if (peerConnection) {
        await peerConnection.addIceCandidate(candidate);
        console.log(`🧊 ICE candidate added for ${fromPlayerId}`);
      }
    } catch (error) {
      console.error(`❌ Failed to add ICE candidate for ${fromPlayerId}:`, error);
    }
  }

  /**
   * 发送信令消息
   */
  sendSignalingMessage(targetPlayerId, data) {
    if (this.isTestMode) {
      // 测试模式：模拟信令延迟
      setTimeout(() => {
        console.log(`🧪 [TEST] Simulating signaling to ${targetPlayerId}:`, data.type);
        this.simulateSignalingResponse(targetPlayerId, data);
      }, this.testConfig.simulateLatency);
    } else {
      // 生产模式：通过WebSocket发送
      const socket = this.store.state.session.socket;
      if (socket) {
        socket.send('webrtc_signal', {
          targetId: targetPlayerId,
          ...data
        });
      }
    }
  }

  /**
   * 模拟信令响应（测试用）
   */
  simulateSignalingResponse(targetPlayerId, data) {
    if (!this.isTestMode) return;

    // 模拟对方的响应
    setTimeout(() => {
      switch (data.type) {
        case 'offer':
          console.log(`🧪 [TEST] Simulating answer from ${targetPlayerId}`);
          // 模拟收到answer
          break;
        case 'answer':
          console.log(`🧪 [TEST] Answer acknowledged by ${targetPlayerId}`);
          break;
        case 'ice-candidate':
          console.log(`🧪 [TEST] ICE candidate acknowledged by ${targetPlayerId}`);
          break;
      }
    }, this.testConfig.simulateLatency);
  }

  /**
   * 播放远程音频
   */
  playRemoteAudio(playerId, stream) {
    // 创建音频元素
    const audioElement = document.createElement('audio');
    audioElement.srcObject = stream;
    audioElement.autoplay = true;
    audioElement.playsInline = true;
    audioElement.id = `remote-audio-${playerId}`;
    
    // 设置音量和空间音频（如果支持）
    audioElement.volume = 0.8;
    
    // 添加到DOM（隐藏）
    audioElement.style.display = 'none';
    document.body.appendChild(audioElement);
    
    console.log(`🔊 Playing remote audio for ${playerId}`);
  }

  /**
   * 断开与指定玩家的连接
   */
  disconnectFromPlayer(playerId) {
    const peerConnection = this.peerConnections.get(playerId);
    if (peerConnection) {
      peerConnection.close();
      this.peerConnections.delete(playerId);
    }

    // 移除远程音频流
    this.remoteStreams.delete(playerId);
    this.store.commit('voiceChat/removeRemoteStream', playerId);

    // 移除音频元素
    const audioElement = document.getElementById(`remote-audio-${playerId}`);
    if (audioElement) {
      audioElement.remove();
    }

    console.log(`🔌 Disconnected from ${playerId}`);
  }

  /**
   * 更新连接状态
   */
  updateConnectionState(playerId, state) {
    let quality = 'unknown';
    
    switch (state) {
      case 'connected':
        quality = 'excellent';
        break;
      case 'connecting':
        quality = 'good';
        break;
      case 'disconnected':
      case 'failed':
        quality = 'poor';
        break;
    }

    this.store.commit('voiceChat/updateConnectionState', {
      playerId,
      connectionState: {
        status: quality,
        ping: this.isTestMode ? Math.floor(Math.random() * 200) + 50 : 0,
        quality,
        timestamp: Date.now()
      }
    });
  }

  /**
   * 处理连接失败
   */
  handleConnectionFailure(playerId) {
    console.warn(`⚠️ Connection failure with ${playerId}, attempting reconnection...`);
    
    // 延迟重连
    setTimeout(() => {
      if (this.isTestMode) {
        console.log(`🧪 [TEST] Simulating reconnection to ${playerId}`);
        this.updateConnectionState(playerId, 'connected');
      } else {
        this.connectToPlayer(playerId, true);
      }
    }, 3000);
  }

  /**
   * 设置本地音频静音
   */
  setMuted(muted) {
    if (this.localStream) {
      this.localStream.getAudioTracks().forEach(track => {
        track.enabled = !muted;
      });
      console.log(`🎤 Local audio ${muted ? 'muted' : 'unmuted'}`);
    }
  }

  /**
   * 设置远程音频音量
   */
  setRemoteVolume(playerId, volume) {
    const audioElement = document.getElementById(`remote-audio-${playerId}`);
    if (audioElement) {
      audioElement.volume = Math.max(0, Math.min(1, volume / 100));
      console.log(`🔊 Remote volume for ${playerId} set to ${volume}%`);
    }
  }

  /**
   * 获取连接统计信息
   */
  async getConnectionStats(playerId) {
    const peerConnection = this.peerConnections.get(playerId);
    if (!peerConnection) return null;

    if (this.isTestMode) {
      // 测试模式：返回模拟数据
      return {
        audioLevel: Math.random() * 100,
        packetsLost: Math.floor(Math.random() * 10),
        jitter: Math.random() * 50,
        roundTripTime: Math.random() * 200 + 50
      };
    }

    try {
      const stats = await peerConnection.getStats();
      const audioStats = {};
      
      stats.forEach(report => {
        if (report.type === 'inbound-rtp' && report.mediaType === 'audio') {
          audioStats.packetsLost = report.packetsLost;
          audioStats.jitter = report.jitter;
        }
        if (report.type === 'candidate-pair' && report.state === 'succeeded') {
          audioStats.roundTripTime = report.currentRoundTripTime;
        }
      });
      
      return audioStats;
    } catch (error) {
      console.error(`❌ Failed to get stats for ${playerId}:`, error);
      return null;
    }
  }

  /**
   * 清理所有连接
   */
  cleanup() {
    // 关闭所有peer连接
    this.peerConnections.forEach((pc, playerId) => {
      this.disconnectFromPlayer(playerId);
    });

    // 停止本地音频流
    if (this.localStream) {
      this.localStream.getTracks().forEach(track => track.stop());
      this.localStream = null;
    }

    console.log('🧹 WebRTC Manager cleaned up');
  }
}

export default WebRTCManager;